package xyz.hubery.listener;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xyz.hubery.model.Constants;
import xyz.hubery.pojo.GoodsDesc;
import xyz.hubery.service.SearchService;

@Slf4j
@Service
@RocketMQMessageListener(
        topic = Constants.SYNC_GOODS_TOPIC,
        consumerGroup = "sync_goods_group",
        consumeMode = ConsumeMode.ORDERLY
)
public class SyncGoodsListener implements RocketMQListener<GoodsDesc>, RocketMQPushConsumerLifecycleListener {



    @Autowired
    private SearchService searchService;


    @Override
    public void prepareStart(DefaultMQPushConsumer defaultMQPushConsumer) {
        // 设置为顺序消费
        defaultMQPushConsumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
    }

    @Override
    public void onMessage(GoodsDesc goodsDesc) {
        if(Constants.SYNC_GOODS_TAG.equals(goodsDesc.getTag())) {
            log.info("同步商品数据到ES中：{}",goodsDesc);
            searchService.syncGoodsToES(goodsDesc);
        }else{
            log.info("删除商品数据：{}",goodsDesc);
            searchService.delete(goodsDesc.getId());
        }
    }
}
